/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Tipo_Animal.java
 *
 * Created on 10/10/2012, 20:47:42
 */

package projeto;

import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import projeto.classes.ModeloTipoAnimal;
import projeto.classes.TipoAnimalAcessaDados;

/**
 *
 * @author Angela
 */
public class Tipo_Animal extends javax.swing.JInternalFrame {

    /** Creates new form Tipo_Animal */
    ModeloTipoAnimal ta;
    TipoAnimalAcessaDados taDao;
    ArrayList<ModeloTipoAnimal> lista;
    
    public Tipo_Animal() {
        //somente admins acessam
        initComponents();
        btnAlterar.setEnabled(false);
        btnExcluir.setEnabled(false);
        txtTipo.setEnabled(false);
        cmbPesquisa.setEnabled(false);
        
        ta = new ModeloTipoAnimal();
        taDao = new TipoAnimalAcessaDados();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtTipo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnConsultar = new javax.swing.JToggleButton();
        txtConsulta = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cmbPesquisa = new javax.swing.JComboBox();
        lblCodigo = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnSair = new javax.swing.JButton();

        setTitle("Entrega Gado - Tipo de Animal");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("TIPO DE ANIMAL");

        txtTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTipoActionPerformed(evt);
            }
        });

        jLabel2.setText("Tipo:");

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        jLabel3.setText("Consultar por:");

        cmbPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbPesquisaActionPerformed(evt);
            }
        });

        lblCodigo.setText("--");

        jLabel4.setText("Código:");

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(cmbPesquisa, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(jLabel1))
                                    .addComponent(txtConsulta))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnConsultar))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblCodigo)
                                    .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(45, 45, 45))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConsultar)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCodigo)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnAlterar)
                    .addComponent(btnSair))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExcluir)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTipoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTipoActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        if (btnNovo.getText().equals("Novo")) {
            txtTipo.setEnabled(true);
            txtTipo.setText("");
            lblCodigo.setText("--");
            btnNovo.setText("Salvar");
            btnAlterar.setEnabled(false);
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
            }
        } else {
            //clicou no salvar
            if (txtTipo.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "Informe o tipo para salvar", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                ta.setTipoAnimal(txtTipo.getText());
                ta.setAnimalId(0);
                
                try {
                    if (!taDao.incluir(ta)) {
                        JOptionPane.showMessageDialog(this, "Dados gravados", "Cliente", JOptionPane.INFORMATION_MESSAGE);
                        btnNovo.setText("Novo");
                        btnAlterar.setEnabled(true);
                        txtTipo.setEnabled(false);
                        int maxId = taDao.consultaMaxId();
                        lblCodigo.setText(maxId + "");
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                            }
                    }
                    
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
                    
            }
            
        }
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (btnAlterar.getText().equals("Alterar")) {
            txtTipo.setEnabled(true);
            btnAlterar.setText("Salvar");
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
            }
        } else {
            if (txtTipo.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Informe o tipo para alterar", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                ta.setId(Integer.parseInt(lblCodigo.getText()));
                ta.setTipoAnimal(txtTipo.getText());
                ta.setAnimalId(0);   
                
                try {
                    if (taDao.alterar(ta) > 0) {
                        JOptionPane.showMessageDialog(this, "Dados alterados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnAlterar.setText("Alterar");
                        txtTipo.setEnabled(false);
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                        }
                    }
                    
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
       if (txtConsulta.getText().isEmpty()) {
           JOptionPane.showMessageDialog(this, "Informe o tipo para consulta", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
       } else {
           //seta o ArrayList para null
           lista = null;
           String filtro = "tp_animal LIKE '" + txtConsulta.getText() + "%'";
        
           try {
            lista = taDao.consulta(filtro);
            
            if (lista.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Não foram localizados tipos com o nome " + txtConsulta.getText(), "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            }
            
            if (lista.size() > 0) {
                //limpa a lista
                if (cmbPesquisa.getItemCount() > 0) {                   
                   cmbPesquisa.removeAllItems();
                }
                cmbPesquisa.setEnabled(true);
                btnAlterar.setEnabled(true);
                btnExcluir.setEnabled(true);
                btnNovo.setText("Novo");
                txtTipo.setEnabled(false);
                
                //seleciona o 1º (ou o unico) item da lista
                ModeloTipoAnimal modeloTa = lista.get(0);
                cmbPesquisa.addItem(modeloTa.getTipoAnimal());
                cmbPesquisa.setSelectedIndex(0);
                cmbPesquisaActionPerformed(evt);   
            }
            
            if (lista.size() > 1) {
                //apenas inclui os outros componentes na lista (se houver)
                for (int i = 1; i <= lista.size() - 1; i++) {
                    ModeloTipoAnimal modeloTa = lista.get(i);
                    cmbPesquisa.addItem(modeloTa.getTipoAnimal());
                }
              }
           } catch (Exception ex) {
               JOptionPane.showMessageDialog(this, "Erro ao consultar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
           }
       }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void cmbPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbPesquisaActionPerformed
        if (evt.getSource().getClass().getSimpleName().equals("JComboBox")) {
            JComboBox cmb = (JComboBox)evt.getSource();
            int index = cmb.getSelectedIndex();
            if (index != -1) {
                ModeloTipoAnimal taModelo = lista.get(index);
                String id = taModelo.getId() + "";
                String tipo = taModelo.getTipoAnimal();
                lblCodigo.setText(id);
                txtTipo.setText(tipo);
            }
        }
    }//GEN-LAST:event_cmbPesquisaActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        if (txtTipo.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Selecione um tipo", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            try {
                int id = Integer.parseInt(lblCodigo.getText());
                
                if (taDao.deletar(id) == 1) {
                    JOptionPane.showMessageDialog(this, "Registro excluido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                    txtTipo.setText("");
                    btnExcluir.setEnabled(false);
                    btnAlterar.setEnabled(false);
                }
                
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao excluir " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnExcluirActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JToggleButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cmbPesquisa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtTipo;
    // End of variables declaration//GEN-END:variables

}
